<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px">
      <el-breadcrumb-item :to="{ path: '/' }">后台管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>

    <div style="margin: 20px 10px">
      角色名称:
      <el-input style="width: 500px;height: 32px" type="text" v-model="wd"></el-input>
      <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
      <el-button type="primary" icon="el-icon-refresh-right" @click="replace()">重置</el-button>
    </div>

    <div style="margin: 20px 10px">
      <el-button type="primary" icon="el-icon-plus" @click="dialogFormVisible = true">新增角色</el-button>


      <el-button type="primary" icon="el-icon-upload2">导入</el-button>
      <el-button type="primary" icon="el-icon-download">导出</el-button>
    </div>

    <!--      新增页面-->
    <el-dialog title="新增" :visible.sync="dialogFormVisible"><hr>
      <el-form :model="role">
        <el-form-item label="角色编码" :label-width="formLabelWidth">
          <el-input v-model="role.coding" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" :label-width="formLabelWidth">
          <el-input v-model="role.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" :label-width="formLabelWidth">
          <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="textarea">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">关 闭</el-button>
        <el-button type="primary" @click="insert();dialogFormVisible = false">确 定</el-button>
      </div>
    </el-dialog>

    <el-divider></el-divider>

    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID"  align="center"></el-table-column>
      <el-table-column prop="name" label="名称" align="center"></el-table-column>
      <el-table-column prop="coding" label="编码" align="center"></el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间"  align="center"></el-table-column>
      <el-table-column prop="gmtModified" label="修改时间" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button @click="loadUserList(scope.row)" type="text" size="small">用户</el-button>

          <el-dialog title="用户列表" :visible.sync="dialogTableVisible1">
            <el-table :data="userData">
              <el-table-column property="username" label="用户名"></el-table-column>
              <el-table-column property="email" label="邮箱"></el-table-column>
              <el-table-column property="unit" label="单位"></el-table-column>
              <el-table-column property="phone" label="手机号码"></el-table-column>
            </el-table>
          </el-dialog>

          <el-button type="text" size="small">
            <el-dropdown>
              <span class="el-dropdown-link">
                更多<i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item  ><a href="javascript:void (0)" @click="addPower(scope.row)">授权</a></el-dropdown-item>

                <el-dropdown-item>
                  <a href="javascript:void(0)" @click="handleEdit(scope.row)">编辑</a>
                </el-dropdown-item>
                <el-dropdown-item><a href="javascript:void (0)" @click="openDeleteConfirm(scope.row)">删除</a></el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
<!--      授权     -->
<!--    <el-dialog title="授权" :visible.sync="dialogFormVisible3">
      <el-form :model="a">
        <el-select v-model="powerForm.ids" multiple placeholder="请选择">
          <el-option
              v-for="item in powerData"
              :key="item.id"
              :label="item.power"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
      </div>
    </el-dialog>-->

    <el-dialog title="编辑角色" :visible.sync="dialogFormVisible2">
      <el-form :model="ruleForm">

        <el-form-item label="名称" :label-width="formLabelWidth">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>

        <el-form-item label="编码" :label-width="formLabelWidth">
          <el-input v-model="ruleForm.coding"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit()">确 定</el-button>
      </div>
    </el-dialog>



    <el-drawer
        title="授权"
        :visible.sync="drawer"
        :with-header="false">

      <el-tree
          :data="arrList"
          show-checkbox
          node-key="id"
          :default-expanded-keys="[1]"
          :highlight-current="true"
          :default-checked-keys="currentNodekey"
          :props="defaultProps"
          @check="currentChecked"
          ref="tree"

          >
      </el-tree>
      <div >
        <el-button @click="getCheckedNodes">确定</el-button>
        <el-button @click="getCheckedKeys">取消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
export default {
  data(){
    return{
      name: "roleList",
      wd:'',
      tableData:[],
      role: {
        name:'',
        coding:''
      },
      dialogTableVisible: false,
      dialogFormVisible: false,
      formLabelWidth: '120px',
      textarea:'',
      dialogTableVisible1: false,
      userData:[],
      dialogFormVisible2: false,
      ruleForm:{
        name:'',
        coding:''
      },
      dialogFormVisible3: false,
   /*   powerData:[],*/

      drawer: false,
      currentNodekey: [1,2,3,4,5,6],
      rolePower:{},

      arrList: [

      ],

      defaultProps: {
        id:'id',
        children: 'children',
        label: 'label'
      },



    }
  },
  methods:{


    /*授权*/
    addPower(r){
      // 执行方法1

      this.method1(r).then(() => {
            // 方法2
        this.lastMethod();
      });

    },
    method1(r){
      return new Promise((resolve,reject) => {
        /* 显示 */
        this.currentNodekey=[]

        let urls='http://localhost:8080/roles/power/exist/'+r.id;
        this.axios
            .create({'headers':{'Authorization':localStorage.getItem('jwt')}})
            .get(urls).then((response)=>{
          this.currentNodekey=response.data.data
          console.log("2222currentNodekey="+this.currentNodekey)
          console.log("r.data.data="+response.data.data)
          this.$nextTick(() => {
            this.$refs.tree.setCheckedKeys(this.currentNodekey);
          });

          resolve(this.detail_method1)
        })
        console.log("r:==="+r.id)
        this.rolePower.roleId=r.id;
      });

    },
    lastMethod(){
      this.drawer= true;
      console.log("currentNodekey="+this.currentNodekey)

    },
    /* 关闭选择权限 */
    getCheckedKeys(){
      this.drawer= false;
      this.rolePower={};
    },
    /* 修改权限 */
    getCheckedNodes(){
      let url='http://localhost:8080/roles/update/rolePower';
      let a=this.qs.stringify(this.rolePower)
      this.axios
          .create({'headers':{'Authorization':localStorage.getItem('jwt')}})
          .post(url,a).then((response)=>{
            if (response.data.state==20000){
              this.$message({
                message: '修改权限成功！',
                type: 'success'
              });
              this.drawer= false;
            }else {
              this.$message.error(response.data.message);
            }
      });

    },
    /* 选中的权限 */
    currentChecked (nodeObj, SelectedObj) {
      this.rolePower.powers=SelectedObj.checkedKeys;
      console.log(SelectedObj.checkedKeys)   // 这是选中的节点的key数组
    },
    loadPowerList(){
      let url='http://localhost:8080/roles/power';
      this.axios
          .create({'headers':{'Authorization':localStorage.getItem('jwt')}})
          .get(url).then((response)=>{
        let a=response.data.data;

        for (let i = 0; i <a.length; i++) {
          this.arrList.push({id:0,label:'',children:[]});
          let arr=this.arrList[i];
          arr.id=a[i].id;
          arr.label=a[i].power;

          let url="http://localhost:8080/roles/power/son/"+a[i].id;
          this.axios
              .create({'headers':{'Authorization':localStorage.getItem('jwt')}})
              .get(url).then((r)=>{
            let b=r.data.data;
            for (let j = 0; j <b.length ; j++) {
              arr.children.push({id:0,label:''});
              let c=arr.children[j];
              c.id=b[j].id;
              c.label=b[j].power;
            }
          })
        }
      })
    },
    /*根据角色id查询对应的用户*/
    loadUserList(role){
      this.dialogTableVisible1 = true;
      console.log(this.tableData);
      let url = 'http://localhost:8080/roles/'+role.id+'/selectByRoleId';
      this.axios
          .create({
            'headers':{
              'Authorization':localStorage.getItem('jwt')
            }
          })
          .get(url).then((response)=>{
            let responseBody = response.data;
            this.userData = responseBody.data;
      })
    },
    /*编辑*/
    submitEdit(){
      let url = 'http://localhost:8080/roles/update/'+this.ruleForm.id;
      console.log(url);
      let formData = this.qs.stringify(this.ruleForm);
      this.axios
          .create({
            'headers':{
              'Authorization':localStorage.getItem('jwt')
            }
          })
          .post(url,formData).then((response) => {
        let responseBody = response.data;
        if(responseBody.state == 20000){
          this.$message({
            message: '修改角色成功！',
            type: 'success'
          });
          this.dialogFormVisible2 = false;
          this.loadRoleList();
        } else  {
          this.$message.error(responseBody.message);
        }
      })
    },
    handleEdit(role){
      let message = '编辑'+role.name+'角色';
      console.log(message);
      //this.dialogFormVisible2 = true;
      //this.ruleForm = role;
      let url = 'http://localhost:8080/roles/selectById/'+ role.id;
      console.log(url);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
            let responseBody = response.data;
        if(responseBody.state == 20000){
          this.ruleForm = responseBody.data;
          console.log(this.ruleForm);
          this.dialogFormVisible2 = true;
        }else {
          this.$message.error(responseBody.message);
          this.loadRoleList();
        }
      })
    },
    /*新增*/
    insert(){
      let url = 'http://localhost:8080/roles/add-new';
      console.log('url = '+url);
      let formData = this.qs.stringify(this.role);
      console.log('formData = ' +formData)
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url,formData).then((response)=> {
          let responseBody = response.data;
          formData = responseBody.data;
          this.loadRoleList();
      })
    },
    /*重置*/
    replace(){
      this.wd="";
      this.loadRoleList();
    },
    /*模糊查询全部*/
    search(){
      let url = 'http://localhost:8080/roles/selectByWd'+'/'+this.wd;
      console.log('url = '+url);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url).then((response)=> {
        console.log('wd='+this.wd)
        let responseBody = response.data;
        this.tableData = responseBody.data;
      })
    },
    /*编辑角色*/
    /*删除角色*/
    openDeleteConfirm(role){
      let message = '此操作将永久删除['+ role.name +']文件, 是否继续?'
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(role);
      }).catch(() => {
      });
    },
    handleDelete(role){
      let url = 'http://localhost:8080/roles/'+role.id+'/delete';
      console.log('url = ' +url);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url).then((response)=>{
          let responseBody = response.data;
        if(responseBody.state == 20000){
          this.loadRoleList();
        }else {
          this.$message.error(responseBody.message);
          this.loadRoleList();
        }
      })
    },
    /*角色列表*/
    loadRoleList(){
      let url = 'http://localhost:8080/roles';
      console.log('url = '+url);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response)=>{
        let responseBody = response.data;
        this.tableData = responseBody.data;
      })
    },






  },
  mounted(){
    console.log('muonted');
    this.loadPowerList();
    this.loadRoleList();
  },

}
</script>

<style >
  .el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
  font-size: small;
  }
  .el-icon-arrow-down {
  font-size: 12px;
  }
  .el-tree-node.is-current > .el-tree-node__content {

    background-color: #c2d6ea !important;

  }
</style>
